package guowei.guliproduct.product.exception;

import guowei.common.exception.BizCodeEnume;
import guowei.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 全局异常处理器，若后端结果校验报错就会被处理
 */
@RestControllerAdvice(basePackages = "guowei.guliproduct.product")
@Slf4j
public class GlobalException {

    /**
     * 精确匹配
     * 单独处理MethodArgumentNotValidException异常 若后端检验结果出错，就会报错
     * @param methodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerException0(MethodArgumentNotValidException methodArgumentNotValidException){

        HashMap<String, String> map = new HashMap<>();
        BindingResult result = methodArgumentNotValidException.getBindingResult();
        result.getFieldErrors().forEach((item)->{
            map.put(item.getDefaultMessage(),item.getField());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    };

    /**
     * 广义匹配
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException1(Throwable exception){
        return R.error(BizCodeEnume.UNKNOWN_EXCEPTION.getCode(), BizCodeEnume.UNKNOWN_EXCEPTION.getMsg());
    }

}
